package com.xyh.transaction.queue;

import com.xyh.transaction.entity.Order;
import com.xyh.transaction.exception.BusinessException;
import com.xyh.transaction.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class OrderDelayQueue {

    @Autowired
    private RedisUtil redisUtil;

    // 延迟队列 Redis Key，支持动态配置
    @Value("${redis.key.delayQueue}")
    private String key;

    // 添加订单到延迟队列
    public void addToDelayQueue(Order order, Long expiredTime) {
        long score = System.currentTimeMillis() + expiredTime;
        String value = order.getId() + "_" + order.getOrderNo();
        redisUtil.zsetAdd(key, value, score);
    }

    // 获取到期的订单
    public Collection<String> getExpiredOrders() {
        long currentTimeMillis = System.currentTimeMillis();
        // 查询到期的订单
        Set<Object> expiredOrders = redisUtil.zsetRangeByScore(key, 0, currentTimeMillis);
        if (expiredOrders.isEmpty()) {
            return Collections.emptyList();
        }
        // 简化序列化逻辑
        return expiredOrders.stream()
                .map(Object::toString)
                .collect(Collectors.toList());
    }

    // 移除已处理的订单
    public void removeProcessedOrder(String orderIdAndNoStr) {
        redisUtil.zsetRemove(key, orderIdAndNoStr);
    }

    // 获取订单的过期时间
    public long getExpiredTime(String orderIdAndNoStr) {
        Long score = redisUtil.zsetScore(key, orderIdAndNoStr);
        if (score == null) {
            throw new BusinessException("订单【" + orderIdAndNoStr.split("_")[1] + "】不存在或已过期！");
        }
        return score;
    }
}

